package com.ka.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.ka.dialog.MoneyDialog;
import com.ka.dialog.MoneyDialog.AddMoneyEvent;
import com.ka.lifemanagement.R;
import com.ka.model.ActivityModel;
import com.ka.model.GeneralModel;
import com.ka.provider.Type;
import com.ka.provider.Type.EventType;
import com.ka.provider.Type.SunTime;

public class Component01 extends LinearLayout implements AddMoneyEvent {

	protected Spinner spinner;
	protected ArrayAdapter<String> adapter;
	protected EditText title;
	protected ImageView edit;
	protected Type.SunTime suntimeType;
	public Component01Delegate delegate;
	protected MoneyDialog dialog;
	protected EventType eventType;
	protected List<String> sugList;

	public interface Component01Delegate {
		public void addNewComponent(SunTime suntime);

		public void removeComponent(Component01 com);
	}

	public GeneralModel getModel() {
		GeneralModel model = new ActivityModel();

		((ActivityModel) model).setName(title.getText().toString());
		((ActivityModel) model).setPrice(Integer.parseInt(spinner
				.getSelectedItem().toString()));
		((ActivityModel) model).setPrice_type(0);
		((ActivityModel) model).setTime(new Date());

		return model;
	}

	public Component01(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.suntimeType = SunTime.None;
		if (!isInEditMode()) {
			initialize(context);
			execution();
		}

	}

	public Component01(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public Component01(Context context) {
		super(context);
		this.suntimeType = SunTime.None;
		if (!isInEditMode()) {
			initialize(context);
			execution();
		}
	}

	public Component01(Context context, SunTime suntimeType) {
		super(context);
		this.suntimeType = suntimeType;
		if (!isInEditMode()) {
			initialize(context);
			execution();
		}
	}

	private void execution() {

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		edit.setOnClickListener(editListener);
		title.addTextChangedListener(watcherEvent);
		edit.setVisibility(View.INVISIBLE);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Log.d("Spiner touch", arg2 + "");
				Log.d("Spiner touch id", arg3 + "");

				if (4 == arg3) {

					dialog.delegate = Component01.this;
					dialog.show(((Activity) getContext()).getFragmentManager(),
							"tag");
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});

		title.setLongClickable(false);
		title.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				// Drawable co = title.getCompoundDrawables()[2];
				// if (co == null) {
				// return false;
				// }
				// if (event.getAction() != MotionEvent.ACTION_DOWN) {
				// return false;
				// }
				// if (event.getX() > title.getMeasuredWidth()
				// - title.getPaddingRight() - co.getIntrinsicWidth()) {
				// Toast.makeText(getContext(), "Capture", Toast.LENGTH_SHORT)
				// .show();
				// return true;
				// } else {
				// return false;
				// }
				// final int DRAWABLE_LEFT = 0;
				// final int DRAWABLE_TOP = 1;
				final int DRAWABLE_RIGHT = 2;
				// final int DRAWABLE_BOTTOM = 3;

				if (event.getAction() == MotionEvent.ACTION_UP) {

					if (event.getRawX() >= (title.getRight() - title
							.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds()
							.width())) {
						// your action here

						Toast.makeText(getContext(), "Capture",
								Toast.LENGTH_LONG).show();

						return true;
					}
				}
				return false;
			}
		});

	}

	private void initialize(Context context) {
		eventType = EventType.Add;

		dialog = new MoneyDialog();

		LayoutInflater lif = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		lif.inflate(R.layout.component01, this);

		spinner = (Spinner) this.findViewById(R.id.activity_price);

		sugList = new ArrayList<String>(Arrays.asList(getResources()
				.getStringArray(R.array.value)));

		// adapter = ArrayAdapter.createFromResource(context, R.array.value,
		// android.R.layout.simple_spinner_item);

		adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item, sugList);

		title = (EditText) this.findViewById(R.id.activity_title);
		edit = (ImageView) this.findViewById(R.id.acitivty_edit);

		this.setSaveEnabled(true);
	}

	OnClickListener editListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (delegate != null) {

				switch (eventType) {
				case Edit:
					delegate.removeComponent(Component01.this);

					break;
				case Add:

					applyType(EventType.Edit);
					delegate.addNewComponent(suntimeType);
					break;
				default:
					break;
				}

			}
		}

	};

	private void applyType(EventType type) {
		eventType = type;
		switch (eventType) {
		case Edit:
			edit.setImageResource(R.drawable.ic_remove_component);
			break;
		case Add:
			edit.setImageResource(R.drawable.ic_add_new_component);
			break;
		default:
			break;
		}
	}

	public int getValue() {
		if (title.getText().toString().trim().equals(""))
			return 0;
		return Integer.parseInt(spinner.getSelectedItem().toString());
	}

	TextWatcher watcherEvent = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			Log.d(Component01.class.toString(), "text change "
					+ title.getText().toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			Log.d(Component01.class.toString(), "before text change"
					+ title.getText().toString());
		}

		@Override
		public void afterTextChanged(Editable s) {
			Log.d(Component01.class.toString(), "after text change"
					+ title.getText().toString());

			if (title.getText().toString().trim().equals("")) {
				edit.setVisibility(View.INVISIBLE);
			} else
				edit.setVisibility(View.VISIBLE);
		}
	};

	@Override
	public void okEvent(String val) {

		if (val.equals("")) {
			spinner.setSelection(0);
			dialog.dismiss();
			return;
		}

		Toast.makeText(this.getContext(), val, Toast.LENGTH_SHORT).show();

		sugList.add(0, val);
		int count = adapter.getCount();
		sugList.remove(count - 2);
		adapter.notifyDataSetChanged();
		dialog.dismiss();
		spinner.setSelection(0);
	}

	@Override
	public void cancelEvent() {
		spinner.setSelection(0);
	}

}
